package com.aliyun.messagemgt.util;

import com.aliyun.messagemgt.common.constant.UrlConstant;
import com.aliyun.messagemgt.common.dto.send.DingTalkMobileDTO;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: DingTalkUtils
 * @Description:
 * @Author: wugongzi
 * @Date: 2021/9/2 15:10
 * @Version: 1.0
 */
@Slf4j
public class DingTalkUtils {

    /**
     * 获取access_token
     *
     * @param appKey
     * @param appSecret
     * @return
     * @throws ApiException
     */
    public static String getAccessToken(String appKey, String appSecret) {
        DefaultDingTalkClient client = new DefaultDingTalkClient(UrlConstant.GET_ACCESS_TOKEN_URL);
        OapiGettokenRequest request = new OapiGettokenRequest();

        request.setAppkey(appKey);
        request.setAppsecret(appSecret);
        request.setHttpMethod("GET");
        OapiGettokenResponse response = null;
        try {
            response = client.execute(request);
        }catch (Exception e){
            log.error(" 获取钉钉token时出现错误 {} ",e.toString());
        }
        return response.getAccessToken();
    }

    /**
     * 根据手机号获取userid
     *
     * @param dingTalkMobileDTO
     * @return
     * @throws ApiException
     */
    public static String getUserIdByMobile(DingTalkMobileDTO dingTalkMobileDTO) {
        DingTalkClient client = new DefaultDingTalkClient(UrlConstant.GET_USER_ID_BY_MOBILE);
        OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
        req.setMobile(dingTalkMobileDTO.getMobile());
        String accessToken = getAccessToken(dingTalkMobileDTO.getAppKey(), dingTalkMobileDTO.getAppSecret());
        OapiV2UserGetbymobileResponse rsp = null;
        try {
            rsp = client.execute(req, accessToken);
        } catch (ApiException e) {
            log.error(" 获取钉钉用户钉钉id时出现错误 {} ", e);
        }

        return rsp.getBody();
    }
}
